package com.feilong.edgeAI.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.aiibt.common.util.Constant;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.model.AskFeilong;
import com.feilong.edgeAI.model.BlueConnect;
import com.feilong.edgeAI.service.FeiLongService;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.EdgeManager;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * allgo蓝牙设备列表
 */
@Route(path = Constant.ACTIVITY_URL_DEVICELIST)
public class DeviceListActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    static class Adapter extends ArrayAdapter<DeviceInfo> {
        private final int myResource;

        public Adapter(@NonNull Context context, int resource, List<DeviceInfo> deviceListData) {
            super(context, resource, deviceListData);
            myResource = resource;
        }

        @SuppressLint("DefaultLocale")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            DeviceInfo deviceInfo = getItem(position);
            String name = "";
            int rssi = 0;
            if (deviceInfo != null) {
                name = deviceInfo.name;
                rssi = deviceInfo.rssi;
            }
            @SuppressLint("ViewHolder") View view = LayoutInflater.from(getContext()).inflate(myResource, parent, false);
            ImageView headImg = view.findViewById(R.id.iv_type);
            if (name == null || name.equals("")) {
                headImg.setImageResource(R.mipmap.ble);
            } else if (
                    (name.startsWith("@") && (name.length() == 11)) ||
                            (name.startsWith("BT_") && (name.length() == 15))
            ) {
                headImg.setImageResource(R.mipmap.ecble);
            } else {
                headImg.setImageResource(R.mipmap.ble);
            }
            ((TextView) view.findViewById(R.id.tv_name)).setText(name);
            ((TextView) view.findViewById(R.id.tv_rssi)).setText(String.format("%d", rssi));
            ImageView rssiImg = view.findViewById(R.id.iv_rssi);
            if (rssi >= -41) rssiImg.setImageResource(R.mipmap.s5);
            else if (rssi >= -55) rssiImg.setImageResource(R.mipmap.s4);
            else if (rssi >= -65) rssiImg.setImageResource(R.mipmap.s3);
            else if (rssi >= -75) rssiImg.setImageResource(R.mipmap.s2);
            else rssiImg.setImageResource(R.mipmap.s1);
            return view;
        }
    }

    List<DeviceInfo> deviceListData = new ArrayList<>();
    List<DeviceInfo> deviceListDataShow = new ArrayList<>();
    Adapter listViewAdapter = null;
    ProgressDialog connectDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_devicelist);
        BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueAdapter != null && blueAdapter.isEnabled()) {
        } else {
            EdgeManager.getInstance().openBluetooth();
        }
        uiInit();
        requestPermissions1();
//        permissionsInit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        deviceListData.clear();
        deviceListDataShow.clear();
        listViewAdapter.notifyDataSetChanged();
    }


    private void requestPermissions1() {
        XXPermissions.with(this)
                .permission(Manifest.permission.BLUETOOTH_SCAN)
                .permission(Manifest.permission.BLUETOOTH_ADVERTISE)
                .permission(Manifest.permission.BLUETOOTH_CONNECT)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION)
                // 申请多个权限
//                .permission(Permission.Group.CALENDAR)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all) {
                            openBluetoothAdapter();
                        } else {
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
    }


    @Override
    protected void onStop() {
        super.onStop();
//        ECBLE.stopBluetoothDevicesDiscovery(this);
    }

    SwipeRefreshLayout swipeRefreshLayout;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            hideConnectDialog();
            ToastUtils.showShort(R.string.connect_bluetooch_fail);
        }
    };
    void uiInit() {
        swipeRefreshLayout = findViewById(R.id.swipe_layout);
//        swipeRefreshLayout.setColorSchemeColors(0x01a4ef);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            deviceListData.clear();
            deviceListDataShow.clear();
            listViewAdapter.notifyDataSetChanged();
            new Handler().postDelayed(() -> {
                swipeRefreshLayout.setRefreshing(false);
                //权限
                permissionsInit();
            }, 1000);
        });

        ListView listView = findViewById(R.id.list_view);
        listViewAdapter = new Adapter(this, R.layout.list_item, deviceListDataShow);
        listView.setAdapter(listViewAdapter);
        listView.setOnItemClickListener((AdapterView<?> adapterView, View view, int i, long l) -> {
            showConnectDialog();
            DeviceInfo deviceInfo = (DeviceInfo) listView.getItemAtPosition(i);
            EventBus.getDefault().post(deviceInfo);
            handler.sendEmptyMessageDelayed(1,30000);
/*            ECBLE.onBLEConnectionStateChange((boolean ok, int errCode, String errMsg)-> runOnUiThread(()->{
                hideConnectDialog();
                if (ok) {
                    showToast("蓝牙已连接");
                    EventBus.getDefault().post(deviceInfo);
                    listView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
//                            EventBus.getDefault().post(deviceInfo);
                        }
                    },2000);
//                ECBLE.stopBluetoothDevicesDiscovery(this);
//                    startActivities(new Intent[]{new Intent().setClass(this, DeviceActivity.class)});
                } else {
                    showToast("蓝牙连接失败,errCode="+errCode+",errMsg="+errMsg);
                    showAlert("提示","蓝牙连接失败,errCode="+errCode+",errMsg="+errMsg,()->{});
                }
            }));
            ECBLE.createBLEConnection(this,deviceInfo.id);*/
        });
        listRefresh();
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BlueConnect connect) throws RemoteException {
        handler.removeMessages(1);
        hideConnectDialog();
    }

    void listRefresh() {
        new Handler().postDelayed(() -> {
            deviceListDataShow.clear();
            for (DeviceInfo tempDevice : deviceListData) {
                deviceListDataShow.add(new DeviceInfo(tempDevice.id, tempDevice.name, tempDevice.mac, tempDevice.rssi));
            }
            listViewAdapter.notifyDataSetChanged();
            listRefresh();
        }, 400);
    }

    void showAlert(String title, String content, Runnable callback) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton("OK", (dialogInterface, i) ->
                        new Thread(callback).start())
                .setCancelable(false);
//            .create().show();
    }

    void showConnectDialog() {
        if (connectDialog == null) {
            connectDialog = new ProgressDialog(DeviceListActivity.this);
            connectDialog.setMessage("连接中...");
            connectDialog.setCancelable(true);
        }
        connectDialog.show();
    }

    void hideConnectDialog() {
        if (connectDialog != null) connectDialog.dismiss();
    }

    void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    void openBluetoothAdapter() {
        ECBLE.onBluetoothAdapterStateChange((boolean ok, int errCode, String errMsg) -> runOnUiThread(() -> {
            if (!ok) {
                showAlert("提示", "openBluetoothAdapter error,errCode=" + errCode + ",errMsg=" + errMsg, () -> runOnUiThread(() -> {
                    if (errCode == 10001) {
                        //蓝牙开关没有打开
                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                    }
                    if (errCode == 10002) {
                        //定位开关没有打开
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                }));
            } else {
//                showToast("openBluetoothAdapter ok");
                Log.e("openBluetoothAdapter", "ok");
                startBluetoothDevicesDiscovery();
            }
        }));
        ECBLE.openBluetoothAdapter(this);
    }

    void startBluetoothDevicesDiscovery() {
        ECBLE.onBluetoothDeviceFound((String id, String name, String mac, int rssi) -> runOnUiThread(() -> {
            Log.e("Discovery", name + "|" + mac + "|" + rssi);
            boolean isExist = false;
            for (DeviceInfo tempDevice : deviceListData) {
                if (tempDevice.id.equals(id)) {
                    tempDevice.rssi = rssi;
                    tempDevice.name = name;
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                deviceListData.add(new DeviceInfo(id, name, mac, rssi));
            }
        }));
        ECBLE.startBluetoothDevicesDiscovery(this);
    }

    //权限初始化，有权限才能使用蓝牙
    //https://developer.android.google.cn/about/versions/12/features/bluetooth-permissions?hl=zh-cn
    void permissionsInit() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        };
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // 没有权限，进行权限请求
            EasyPermissions.requestPermissions(this, "请打开应用的定位权限", 0, perms);
            return;
        }
        //安卓12或以上，还需要蓝牙连接附近设备的权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            perms = new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.BLUETOOTH_CONNECT
            };
            if (!EasyPermissions.hasPermissions(this, perms)) {
                // 没有蓝牙权限，进行权限请求
                EasyPermissions.requestPermissions(this, "请打开应用的蓝牙权限，允许应用使用蓝牙连接附近的设备", 1, perms);
                return;
            }
            //权限获取成功，可以使用蓝牙
            openBluetoothAdapter();
        } else {
            //权限获取成功，可以使用蓝牙
            openBluetoothAdapter();
        }
    }

    //    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private static final String TAG = "Devicelist";

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted: ");
        openBluetoothAdapter();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //获取权限失败
        Log.e("onPermissionsDenied", "requestCode=" + requestCode);
        for (String perm : perms) {
            Log.e("perm:", perm);
        }

        //获取定位权限失败
        if (requestCode == 0) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("提示")
                    .setRationale("请打开应用的定位权限")
                    .build().show();
        }
        //获取蓝牙连接附近设备的权限失败
        if (requestCode == 1) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("提示")
                    .setRationale("请打开应用的蓝牙权限，允许应用使用蓝牙连接附近的设备")
                    .build().show();
        }
    }

    @AfterPermissionGranted(0)
    private void AfterPermissionGrantedLocation() {
        //定位权限获取成功
        Log.e("AfterPermissionGranted", "Location");
        //安卓12或以上，还需要蓝牙连接附近设备的权限
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
//            String[] perms = {
//                Manifest.permission.BLUETOOTH_SCAN,
//                Manifest.permission.BLUETOOTH_ADVERTISE,
//                Manifest.permission.BLUETOOTH_CONNECT
//            };
//            if (!EasyPermissions.hasPermissions(this, perms)) {
//                // 没有蓝牙权限，进行权限请求
//                EasyPermissions.requestPermissions(this,"请打开应用的蓝牙权限，允许应用使用蓝牙连接附近的设备",1, perms);
//                return;
//            }
//            //权限获取成功，可以使用蓝牙
//            openBluetoothAdapter();
//        }else{
        //权限获取成功，可以使用蓝牙
        openBluetoothAdapter();
//        }
    }

    @AfterPermissionGranted(1)
    private void AfterPermissionGrantedBluetooth() {
        //获取蓝牙连接附近设备的权限，获取成功，安卓12或以上版本需要
        Log.e("AfterPermissionGranted", "Bluetooth");
        //权限获取成功，可以使用蓝牙
        openBluetoothAdapter();
    }

    public static class DeviceInfo {
        String id;
        String name;
        String mac;
        int rssi;

        DeviceInfo(String id, String name, String mac, int rssi) {
            this.id = id;
            this.name = name;
            this.mac = mac;
            this.rssi = rssi;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMac() {
            return mac;
        }

        public void setMac(String mac) {
            this.mac = mac;
        }

        public int getRssi() {
            return rssi;
        }

        public void setRssi(int rssi) {
            this.rssi = rssi;
        }

        @Override
        public String toString() {
            return "DeviceInfo{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", mac='" + mac + '\'' +
                    ", rssi=" + rssi +
                    '}';
        }
    }
}
